package com.lizhivscaomei.wms.application.service.purchase.in;

import com.lizhivscaomei.wms.domain.entity.bills.inout.common.BizType;
import com.lizhivscaomei.wms.domain.entity.bills.inout.common.InOutType;
import com.lizhivscaomei.wms.domain.entity.bills.inout.common.bill.StockBillPassedEvent;
import com.lizhivscaomei.wms.domain.entity.bills.inout.common.notice.NoticeCompletedEvent;
import com.lizhivscaomei.wms.domain.entity.bills.inout.common.notice.NoticeStates;
import com.lizhivscaomei.wms.domain.entity.bills.inout.purchase.in.bill.PurchaseInBill;
import com.lizhivscaomei.wms.domain.entity.bills.inout.purchase.in.notice.PurchaseInNotice;
import com.lizhivscaomei.wms.domain.entity.bills.inout.purchase.in.notice.PurchaseInNoticeRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

/**
 * 采购入库通知单
 */
@Service
public class PurchaseInNoticeManager {
    @Autowired
    private PurchaseInNoticeRepo purchaseInNoticeRepo;
    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    public PurchaseInNotice create() {
        return new PurchaseInNotice();
    }

    public void save(PurchaseInNotice notice) {
        this.purchaseInNoticeRepo.save(notice);
    }

    public void cancel(PurchaseInNotice notice) throws Exception {
        notice.cancel();
        this.purchaseInNoticeRepo.save(notice);
    }

    public void complete(PurchaseInNotice notice) throws Exception {
        notice.complete();
        this.purchaseInNoticeRepo.save(notice);
        //发布完成事件
        this.applicationEventPublisher.publishEvent(new NoticeCompletedEvent(this, notice));
    }

    @TransactionalEventListener(phase = TransactionPhase.BEFORE_COMMIT)
    public void dealBillPassedEvent(StockBillPassedEvent event) throws Exception {
        //只关心采购入库
        if (event.getBill().getInOutType().equals(InOutType.IN) && event.getBill().getBizType().equals(BizType.PURCHASE)) {
            //获取事件采购入库单
            PurchaseInBill purchaseInBill = (PurchaseInBill) event.getBill();
            //根据入库单找到对应的通知单
            PurchaseInNotice notice = this.purchaseInNoticeRepo.getOne(purchaseInBill.getNoticeCode());
            notice.dealBillPassedEvent(event);
            this.purchaseInNoticeRepo.save(notice);
            if (notice.getState().equals(NoticeStates.FINISHED)) {
                //发布完成事件
                this.applicationEventPublisher.publishEvent(new NoticeCompletedEvent(this, notice));
            }
        }
    }
}
